package com.hdsx.spring.tomcat.core;

import com.hdsx.spring.tomcat.handler.HttpHandler;
import com.hdsx.spring.tomcat.servlet.HttpServlet;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.io.InputStream;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Pattern;

/**
 * @author 占贤银
 * time 2024/8/16 15:30
 * description 生命之灯因热情而点燃，生命之舟因拼搏而前行
 */
public class TomcatServer {

    private int port;

    // private static Map<Pattern, String> urlMappings = new HashMap<>(10);

    private static Map<Pattern, HttpServlet> urlMappings = new HashMap<>(10);

    private Properties prop = new Properties();

    public TomcatServer(int port) {
        this.port = port;
    }

    public static void main(String[] args) {
        new TomcatServer(8080).start();
    }

    public void start(){
        try {
            initMapping();
            startServer();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void startServer() {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap server = new ServerBootstrap();
                server.group(bossGroup, workerGroup)
                        .channel(NioServerSocketChannel.class)
                        .handler(new LoggingHandler(LogLevel.INFO))
                        .childHandler(new ChannelInitializer<SocketChannel>() {
                            @Override
                            protected void initChannel(SocketChannel channel)
                            {
                                ChannelPipeline pipeline = channel.pipeline();
                                // 编码
                                pipeline.addLast(new HttpResponseEncoder());
                                // 解码器
                                pipeline.addLast(new HttpRequestDecoder());
                                pipeline.addLast(new HttpHandler());
                            }
                        })
                        .option(ChannelOption.SO_BACKLOG, 128)
                        .childOption(ChannelOption.SO_KEEPALIVE, true);
            ChannelFuture future = server.bind(new InetSocketAddress(this.port)).sync();
            future.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) {
                    if (future.isSuccess()) {
                        System.out.println("Netty服务器已启动，监听端口：" + port);
                    }
                }
            });
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    private void initMapping() {
        InputStream in = null;
        try {
            in = this.getClass()
                    .getClassLoader().getResourceAsStream("web.properties");
            prop.load(in);
            for (Object k : prop.keySet()) {
                String key = k.toString();
                if (key.endsWith(".mapping")) {
                    String mappingKey = key.replace(".mapping", ".classname");
                    String urlPattern = prop.getProperty(key).replaceAll("\\*$", "[\\\\w|\\\\/|\\\\d|\\#|\\$\\%\\+\\-]{1,}");
                    Pattern pattern = Pattern.compile(urlPattern);
                    String className = prop.getProperty(mappingKey);
                    Class<?> aClass = Class.forName(className);
                    if (aClass.isInterface()){
                        continue;
                    }
                    Object instance = aClass.newInstance();
                    if (instance instanceof HttpServlet) {
                        HttpServlet httpServlet = (HttpServlet) instance;
                        //TomcatProxy proxy = new TomcatProxy(httpServlet);
                        //httpServlet = proxy.createProxy();
                        httpServlet.init();
                        urlMappings.put(pattern, httpServlet);
                        return;
                    }
                    throw new RuntimeException("'" + aClass.getName() + "', " + "需要继承HttpServlet才能接收HTTP请求！");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static HttpServlet queryClassNameByPattern(String url) {
        for (Pattern pattern : urlMappings.keySet()) {
            if (pattern.matcher(url).matches()) {
                return urlMappings.get(pattern);
            }
        }
        return null;
    }
}
